<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Users2_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('user', '', TRUE);
        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }
        $this->load->library('authentication');
        $this->load->helper('t');

        $this->loggedUser = $this->authentication->getLoggedUser();
        $this->authentication->redirectIfNotBe(array('HR', 'SC'));
    }

    function index($region = 'all', $title = 'all', $ss = 'all') {
        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;
        $this->load->model('region');
        $regions = $this->region->get_list();

        $viewData['regions'] = $regions;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;
        
        // danh sách SS
        $ssList = $this->user->get_list_by_title(array('SS', 'KAS'), array('status' => 'active'));
        $viewData['ssList'] = $ssList;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'));
                    break;
                case 'Medical': $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'));
                    break;
                    break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles());
        }
        if ($region != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['rsm_code'] == $region) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $region;
        }
        if ($ss != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['supervisor_code'] == $ss) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterSS'] = $ss;
        }


        $viewData['rows'] = $users;


        $this->load->view(get_folder($this->loggedUser->title) . '/users2', $viewData);
    }

    function index2($region = 'all') {

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $this->load->model('region');
        $regions = $this->region->get_list();
        //$regions = array('HCM', 'MEK', 'HNO', 'CEN', 'EAS');
        $viewData['regions'] = $regions;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $users = $this->user->get_list_by_title(array('SD', 'HR', 'SC', 'RSM', 'KAM', 'SS', 'KAS'));

        if ($region != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['rsm_code'] == $region) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $region;
        }


        $viewData['rows'] = $users;


        $this->load->view(get_folder($this->loggedUser->title) . '/users2_2', $viewData);
    }

    function report($region = 'all', $title = 'all', $ss = 'all') {

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $this->load->model('region');
        $regions = $this->region->get_list();
        //$regions = array('HCM', 'MEK', 'HNO', 'CEN', 'EAS');
        $viewData['regions'] = $regions;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;
        
        // danh sách SS
        $ssList = $this->user->get_list_by_title(array('SS', 'KAS'), array('status' => 'active'));
        $viewData['ssList'] = $ssList;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'));
                    break;
                case 'Medical': $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'));
                    break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles());
        }
        if ($region != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['rsm_code'] == $region) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $region;
        }
        if ($ss != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['supervisor_code'] == $ss) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterSS'] = $ss;
        }


        $viewData['rows'] = $users;


        $this->load->view(get_folder($this->loggedUser->title) . '/users2_report_1', $viewData);
    }

    function report2($fields = '*', $startFrom = 0, $perPage = 10, $region = 'all', $title = 'all') {

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $this->load->model('region');
        $regions = $this->region->get_list();
        //$regions = array('HCM', 'MEK', 'HNO', 'CEN', 'EAS');
        $viewData['regions'] = $regions;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'), $fields);
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'), $fields);
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'), $fields);
                    break;
                case 'Medical': $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'), $fields);
                    break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles(), $fields, $startFrom = 0, $perPage = 10);
        }
        if ($region != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['rsm_code'] == $region) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $region;
        }


        return $users;
    }

    function edit($user_id) {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        if ($this->input->post('Command') == 'Edit') {
            // Validation
            $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
            $this->form_validation->set_rules('identity_number', 'Identity No', 'required');
            $this->form_validation->set_rules('name', 'Name', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

            if ($this->form_validation->run() == FALSE) {
                $viewData['messageType'] = 'danger';
                $viewData['message'] = validation_errors();
            } else {
                // thực hiện cập nhật
                $newUser = array(
                    'id' => $user_id,
                    'name' => $this->input->post('name'),
                    //'code' => $this->input->post('code'), // kéo theo nhiều thứ khác
                    'gid' => $this->input->post('gid'),
                    'starting_day' => $this->input->post('starting_day'),
                    'stopping_day' => $this->input->post('stopping_day') != '' ? $this->input->post('stopping_day') : null,
                    'title' => $this->input->post('title'),
                    'location' => $this->input->post('location'),
                    'status' => $this->input->post('status'),
                    'status2' => $this->input->post('status2'),
                    'teamleader_code' => $this->input->post('teamleader_code'),
                    'supervisor_code' => $this->input->post('supervisor_code'),
                    'rsm_code' => $this->input->post('rsm_code'),
                    'identity_number' => $this->input->post('identity_number'),
                    'address' => $this->input->post('address'),
                    'phone' => $this->input->post('phone'),
                    'email' => $this->input->post('email'),
                    'note' => $this->input->post('note'),
                );

                if ($this->input->post('password') != '') {
                    $newUser['password'] = md5($this->input->post('password'));
                }

                $viewData['messageType'] = 'success';
                $message = $this->user->update($newUser);
                
                // nếu có thay thế cho ai đó
                // kiểm tra lại cái title mới trước
                $beReplacedCode = $this->input->post('replace');
                if($newUser['title'] == 'RSM' || $newUser['title'] == 'KAM' || $newUser['title'] == 'SS' || $newUser['title'] == 'KAS')
                {
                    if($beReplacedCode != 'noreplace' && $beReplacedCode != false) // có thêm khác false vì từ NR sang RSM, $beReplacedCode == false, thỏa điều kiện kia
                    {
                        // kiểm tra coi code truyền về có ok không
                        $beReplacedUser = $this->user->get_user_by_code($beReplacedCode);
                        if($beReplacedUser != false)
                        {
                            // tiến hành replace
                            $this->user->replace($beReplacedCode, $newUser['code'], $newUser['title']);
                        }
                    }
                    else
                    {
                        
                    }
                }
                else {
                    if($beReplacedCode != 'noreplace')
                    {
                        $message .= '<br/>Title không hợp lệ để thay thế cho người khác. Hủy thao tác thay thế.';
                        $viewData['messageType'] = 'warning';
                    }
                }
                $viewData['message'] = $message;
            }
        }

        $user = $this->user->get($user_id);
        // nếu là RSM, KAM, SS, KAS thì có thể thay thế cho người khác
        switch ($user['title']) {
            case 'RSM':
                $canReplace = $this->user->get_list_by_title(array('RSM'));
                break;
            case 'KAM':
                $canReplace = $this->user->get_list_by_title(array('KAM'));
                break;
            case 'KAS':
                $canReplace = $this->user->get_list_by_title(array('KAS'));
                break;
            case 'SS':
                $canReplace = $this->user->get_list_by_title(array('SS'));
                break;
        }
        // xóa chính user đang được edit ra khỏi danh sách
        foreach ($canReplace as $key => $value) {
            if($value['code'] == $user['code'])
            {
                unset($canReplace[$key]);
                break;
            }
        }
        $user['canReplace'] = $canReplace;
        $viewData['editUser'] = $user;
        $viewData['titles'] = $this->user->get_enum_values();

        $this->load->model('group_model', '', TRUE);
        $viewData['groups'] = $this->group_model->get_allgroups();

        $tls = $this->user->get_list_by_title(array('NRTL', 'BSTL', 'PGTL', 'MedTL'));
        $sss = $this->user->get_list_by_title(array('SS', 'KAS'));
        $rsms = $this->user->get_list_by_title(array('RSM', 'KAM'));
        $viewData['teamleaders'] = $tls;
        $viewData['supervisors'] = $sss;
        $viewData['rsms'] = $rsms;
        
        $viewData['PreviousUrl'] = $this->input->post('PreviousUrl') == '' ? $this->input->server('HTTP_REFERER', TRUE) : $this->input->post('PreviousUrl');

        $this->load->view(get_folder($this->loggedUser->title) . '/user2_edit', $viewData);
    }
    
    function add() {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        if ($this->input->post('Command') == 'Add') {
            // Validation
            $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
            $this->form_validation->set_rules('identity_number', 'Identity No', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('name', 'Name', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

            if ($this->form_validation->run() == FALSE) {
                $viewData['messageType'] = 'danger';
                $viewData['message'] = validation_errors();
            } else {
                // thực hiện thêm mới
                $newUser = array(
                    //'id' => $user_id,
                    'name' => $this->input->post('name'),
                    'code' => $this->input->post('username'), // kéo theo nhiều thứ khác
                    'username' => $this->input->post('username'),
                    'password' => md5($this->input->post('password')),
                    'gid' => $this->input->post('gid'),
                    'starting_day' => $this->input->post('starting_day'),
                    'stopping_day' => $this->input->post('stopping_day') != '' ? $this->input->post('stopping_day') : null,
                    'title' => $this->input->post('title'),
                    'location' => $this->input->post('location'),
                    'status' => $this->input->post('status'),
                    'status2' => $this->input->post('status2'),
                    'teamleader_code' => $this->input->post('teamleader_code'),
                    'supervisor_code' => $this->input->post('supervisor_code'),
                    'rsm_code' => $this->input->post('rsm_code'),
                    'identity_number' => $this->input->post('identity_number'),
                    'address' => $this->input->post('address'),
                    'phone' => $this->input->post('phone'),
                    'email' => $this->input->post('email'),
                    'note' => $this->input->post('note'),
                );


                $viewData['messageType'] = 'success';
                $message = $this->user->insert($newUser);
                $viewData['message'] = $message;
            }
        }

        //$user = $this->user->get($user_id);
        //$viewData['editUser'] = $user;
        $viewData['titles'] = $this->user->get_enum_values();

        $this->load->model('group_model', '', TRUE);
        $viewData['groups'] = $this->group_model->get_allgroups();

        $tls = $this->user->get_list_by_title(array('NRTL', 'BSTL', 'PGTL', 'MedTL'));
        $sss = $this->user->get_list_by_title(array('SS', 'KAS'));
        $rsms = $this->user->get_list_by_title(array('RSM', 'KAM'));
        $viewData['teamleaders'] = $tls;
        $viewData['supervisors'] = $sss;
        $viewData['rsms'] = $rsms;

        $this->load->view(get_folder($this->loggedUser->title) . '/user2_add', $viewData);
    }

    function aj2() {

        /* DB table to use */
        $sTable = "users";

        $string = "teamleader_code as t1,supervisor_code as s1,rsm_code as r1,rsm_code as region,location,code,title,name,starting_day,stopping_day"
                //. ",(select name from users u2 where users.teamleader_code = u2.code),(select name from users u2 where users.supervisor_code = u2.code),rsm_code,status,status2,identity_number,phone,email,note"
                . ",teamleader_code,supervisor_code,rsm_code,status,status2,identity_number,phone,email,note";
        $string2 = "rsm_code as `region`,location,code,title,name,starting_day,stopping_day"
                //. ",(select name from users u2 where users.teamleader_code = u2.code),(select name from users u2 where users.supervisor_code = u2.code),rsm_code,status,status2,identity_number,phone,email,note"
                . ",teamleader_code,supervisor_code,rsm_code,status,status2,identity_number,phone,email,note";
        $string3 = "rsm_code,location,code,title,name,starting_day,stopping_day"
                //. ",(select name from users u2 where users.teamleader_code = u2.code),(select name from users u2 where users.supervisor_code = u2.code),rsm_code,status,status2,identity_number,phone,email,note"
                . ",teamleader_code,supervisor_code,rsm_code,status,status2,identity_number,phone,email,note";
        $aColumns = explode(',', $string3);
        //$aColumns = array( 'teamleader_code', 'supervisor_code', 'rsm_code');

        /* Indexed column (used for fast and accurate table cardinality) */
        $sIndexColumn = "id";

        /* DB table to use */
        $sTable = "users";

        /* Database connection information */
        $gaSql['user'] = "hrsoft";
        $gaSql['password'] = "hr@123456";
        $gaSql['db'] = "hrsoft";
        $gaSql['server'] = "localhost";


        /*         * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * If you just want to use the basic configuration for DataTables with PHP server-side, there is
         * no need to edit below this line
         */

        /*
         * Local functions
         */

        function fatal_error($sErrorMessage = '') {
            header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
            die($sErrorMessage);
        }

        /*
         * MySQL connection
         */
        if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
            fatal_error('Could not open connection to server');
        }

        if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
            fatal_error('Could not select database ');
        }


        /*
         * Paging
         */
        $sLimit = "";
        if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
            $sLimit = "LIMIT " . intval($_GET['iDisplayStart']) . ", " .
                    intval($_GET['iDisplayLength']);
        }


        /*
         * Ordering
         */
        $sOrder = "";
        if (isset($_GET['iSortCol_0'])) {
            $sOrder = "ORDER BY  ";
            for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                    " . ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
                }
            }

            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == "ORDER BY") {
                $sOrder = "";
            }
        }


        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */
        $sWhere = "WHERE ( title not in ('SD', 'HR', 'SC', 'RSM', 'KAM', 'SS', 'KAS')";
        $sWhere .= (isset($_GET['region']) && $_GET['region'] != 'all' ? " and $sTable.rsm_code = '" . $_GET['region'] . "'" : '');
        $sWhere .= (isset($_GET['title']) && $_GET['title'] != 'all' ? " and title = '" . $_GET['title'] . "'" : '');
        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
            $sWhere .= " and (";
            for ($i = 0; $i < count($aColumns); $i++) {
                if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true") {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
                }
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }
        $sWhere .= ')'; //  and users.rsm_code = region.rsm_code

        /* Individual column filtering */
        for ($i = 0; $i < count($aColumns); $i++) {
            if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
                if ($sWhere == "") {
                    $sWhere = "WHERE ";
                } else {
                    $sWhere .= " AND ";
                }
                $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
            }
        }


        /*
         * SQL queries
         * Get data to display
         */
        $sQuery = "
        SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . "
        FROM $sTable
        $sWhere 
        $sOrder
        $sLimit
    ";
        $rResult = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());

        /* Data set length after filtering */
        $sQuery = "
        SELECT FOUND_ROWS()
    ";
        $rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
        $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $iFilteredTotal = $aResultFilterTotal[0];

        /* Total data set length */
        $sQuery = "
        SELECT COUNT(" . $sIndexColumn . ")
        FROM   $sTable
    ";
        $rResultTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
        $aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = $aResultTotal[0];

        $users = $this->report2($string2, intval($_GET['iDisplayStart']), intval($_GET['iDisplayLength']));
        foreach ($users as $key => $value) {
            $users[$key] = array_values($value);
        }

        /*
         * Output
         */
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iFilteredTotal,
            "aaData" => $users//array()//
        );

        //while ($aRow = mysql_fetch_array($rResult)) {
//        foreach ($users as $aRow) {
//            $row = array();
//            for ($i = 0; $i < count($aColumns); $i++) {
//                if ($aColumns[$i] == "version") {
//                    /* Special output formatting for 'version' column */
//                    $row[] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
//                } else if ($aColumns[$i] != ' ') {
//                    /* General output */
//                    $row[] = $aRow[$aColumns[$i]];
//                }
//            }
//            $output['aaData'][] = $row;
//        }

        echo json_encode($output);
    }
    
    function import() {
        
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->helper('xlsimport/php-excel-reader/excel_reader2');
        $this->load->helper('xlsimport/spreadsheetreader.php');
        
        if ($this->input->post('Command') == 'Upload') {
            $allxlsdata = getUploadData();
            if($allxlsdata != false)
            {
                if ($this->input->post('UploadPurpose') == 'Add')
                {
                    $result = $this->user->import($allxlsdata);
                    if($result['success'] != true)
                    {
                        $viewData['message'] = "Những dòng không import được: <br/>".implode(', ', $result['data'])."<br/>Có thể do trùng Code. Hãy kiểm tra lại.";
                        $viewData['messageType'] = 'danger';
                    }
                    else {
                        $viewData['message'] = "Đã import xong.";
                        $viewData['messageType'] = 'success';
                    }
                }
                elseif ($this->input->post('UploadPurpose') == 'Edit') {
                    $result = $this->user->importUpdate($allxlsdata);
                    if($result['success'] != true)
                    {
                        $viewData['message'] = "Những dòng không cập nhật được: <br/>".implode(', ', $result['data']);//."<br/>Có thể do trùng Code. Hãy kiểm tra lại.";
                        $viewData['messageType'] = 'danger';
                    }
                    else {
                        $viewData['message'] = "Đã cập nhật xong.";
                        $viewData['messageType'] = 'success';
                    }
                }
                else {
                    $viewData['message'] = "Không rõ mục đích import.";
                    $viewData['messageType'] = 'danger';
                }
                
            }else
            {
                $viewData['message'] = "Không đọc được file.";
                $viewData['messageType'] = 'danger';
            }
            
            $viewData['UploadPurpose'] = $this->input->post('UploadPurpose');
        }
        
        $this->load->view(get_folder($this->loggedUser->title) . '/users2_import', $viewData);
    }

    function users_report($limit = '0') {

//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }

        $data['result'] = $this->user_list->user_list_all($limit);

        $data['title'] = "User list";

        $data['limit'] = $limit;



        $this->load->view(get_folder($this->loggedUser->title) . '/users_report', $data);
    }

    function remove_user($id) {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }



        $this->user_list->remove_user($id);



        redirect(get_folder($this->loggedUser->title) . '/users', 'refresh');
    }

// add new user form

    function add_new($resultstatus = '') {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $data['resultstatus'] = $resultstatus;

        $data['title'] = "Thêm nhân viên mới";

        $data['su'] = $logged_in['title'];

        $data['title_user'] = $this->user_list->get_enum_values();

        //get the list of the groups

        $data['allgroups'] = $this->group_model->get_allgroups();

        //$this->load->view('header', $data);

        $this->load->view(get_folder($this->loggedUser->title) . '/add_user', $data);

        //$this->load->view('footer', $data);
    }

// insert user into database

    function insert_user() {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|is_unique[users.username]');

        $this->form_validation->set_rules('identity_number', 'Identity No', 'required');

        $this->form_validation->set_rules('name', 'Name', 'required');

        $this->form_validation->set_rules('user_email', 'Email', 'required|valid_email|is_unique[users.email]');

        if ($this->form_validation->run() == FALSE) {

            $this->add_new();
        } else {

            $resultstatus = $this->user_list->insert_user();

            $this->add_new($resultstatus);
        }
    }

    function getCodeRSM() {

        echo $this->user_list->getCodeTitleRSM();

        exit;
    }

    function getCodeSS() {

        echo $this->user_list->getCodeTitleSS();

        exit;
    }

    function getCodeTL() {

        echo $this->user_list->getCodeTitleTL();

        exit;
    }

    // edit the user form

    public function edit_user($user_id, $resultstatus = '') {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $logged_in = $this->session->userdata('logged_in');

        $data['title'] = "Edit User";

        $data['resultstatus'] = $resultstatus;

        $data['user'] = $this->user->get_user($user_id);

        $data['title_user'] = $this->user_list->get_enum_values();

        $data['allgroups'] = $this->group_model->get_allgroups();

        $data['user_id'] = $user_id;

        $data['su'] = $logged_in['su'];

        $this->load->view(get_folder($this->loggedUser->title) . '/edit_user', $data);
    }

    // edit the user form

    public function my_account($resultstatus = '') {

        $data['title'] = "Edit User";

        $logged_in = $this->session->userdata('logged_in');

        $user_id = $logged_in['id'];

        $data['user'] = $this->user->get_user($logged_in['id']);

        $data['allgroups'] = $this->group_model->get_allgroups();

        $data['user_id'] = $user_id;

        $data['resultstatus'] = $resultstatus;

        $data['su'] = $logged_in['su'];

        $this->load->view('header', $data);

        $this->load->view('edit_user', $data);

        $this->load->view('footer', $data);
    }

    // update user in database

    function update_user($user_id) {

        // form validations

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['su'] == "0") {

            $user_id = $logged_in['id'];
        }

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');

        $this->form_validation->set_rules('identity_number', 'Identity No', 'required');

        $this->form_validation->set_rules('name', 'Name', 'required');

        $this->form_validation->set_rules('user_email', 'Email', 'required|valid_email');



        if ($this->form_validation->run() == FALSE) {

            $this->edit_user($user_id);
        } else {

            $resultstatus = $this->user_list->update_user($user_id);

            $this->edit_user($user_id, $resultstatus);
        }
    }

}
